package com.sdy.hospitalguard.h5.util;

import com.sdy.hospitalguard.biz.model.HospitalUser;

import java.text.SimpleDateFormat;
import java.util.Date;

/**
 * @author: 王越洋
 * @version: v1.0
 * @description: com.sdy.hospitalguard.biz.utils
 * @date:2020/5/9
 */
public class CardAnalysis {

    public static HospitalUser getCard(String card) throws Exception {
        HospitalUser hospitalUser = new HospitalUser();
        if (card.length() == 18){
            hospitalUser = getCarInfo18W(card);
        }if(card.length() == 15){
            hospitalUser = getCarInfo15W(card);
        }
        return hospitalUser;
    }

    /**
     * 18位身份证
     * @param cardCode
     * @return
     * @throws Exception
     */
    private static HospitalUser getCarInfo18W(String cardCode)
            throws Exception {
        HospitalUser hospitalUser = new HospitalUser();
        String year = cardCode.substring(6).substring(0, 4);
        String yue = cardCode.substring(10).substring(0, 2);
        Integer sex;
        if (Integer.parseInt(cardCode.substring(16).substring(0, 1)) % 2 == 0) {
            sex = 1;
        } else {
            sex = 0;
        }
        Date date = new Date();
        SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd");
        String fyear = format.format(date).substring(0, 4);
        String fyue = format.format(date).substring(5, 7);
        int age = 0;
        if (Integer.parseInt(yue) <= Integer.parseInt(fyue)) {
            age = Integer.parseInt(fyear) - Integer.parseInt(year) + 1;
        } else {
            age = Integer.parseInt(fyear) - Integer.parseInt(year);
        }
        hospitalUser.setSex(sex);
        hospitalUser.setAge(age);
        return hospitalUser;
    }

    /**
     * 15位身份证
     * @param cardCode
     * @return
     * @throws Exception
     */
    private static HospitalUser getCarInfo15W(String cardCode)
            throws Exception {
        HospitalUser hospitalUser = new HospitalUser();
        String uyear = "19" + cardCode.substring(6, 8);
        String uyue = cardCode.substring(8, 10);
        String usex = cardCode.substring(14, 15);
        Integer sex;
        if (Integer.parseInt(usex) % 2 == 0) {
            sex = 1;
        } else {
            sex = 0;
        }
        Date date = new Date();
        SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd");
        String fyear = format.format(date).substring(0, 4);
        String fyue = format.format(date).substring(5, 7);
        int age = 0;
        if (Integer.parseInt(uyue) <= Integer.parseInt(fyue)) {
            age = Integer.parseInt(fyear) - Integer.parseInt(uyear) + 1;
        } else {
            age = Integer.parseInt(fyear) - Integer.parseInt(uyear);
        }
        hospitalUser.setSex(sex);
        hospitalUser.setAge(age);
        return hospitalUser;
    }

}
